/*
 * @Author: sjf 1758142861@qq.com
 * @Date: 2023-03-24 17:57:37
 * @LastEditors: sjf 1758142861@qq.com
 * @LastEditTime: 2023-03-26 19:21:20
 * @FilePath: /sjf/lwp/posix_sem/mutex.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

/*
该文件模拟的是自己定义的关于锁的应用
即只需要单一的调用LockGuard函数进行加锁
不需要再额外的解锁，避免了忘记解锁的问题
*/
#pragma once

#include <iostream>
#include <pthread.h>

class Mutex
{
public:
    Mutex(pthread_mutex_t *lock = nullptr) : _lock(lock)
    {}
    ~Mutex()
    {}
    void lock() { if (_lock) pthread_mutex_lock(_lock); }
    void unlock() { if (_lock) pthread_mutex_unlock(_lock); }
private:
    pthread_mutex_t *_lock;
};

class LockGuard
{
public:
    LockGuard(pthread_mutex_t *mutex) : _mutex(mutex)
    {
        _mutex.lock();
    }
    ~LockGuard() { _mutex.unlock(); }
private:
    Mutex _mutex;
};

// // C++中
// template <class Lock>
// class LockGuard
// {
// public:
//     LockGuard(Lock &lk) : _lk(lk)
//     {
//         _lk.lock();
//     }
//     ~LockGuard()
//     {
//         _lk.unlock();
//     }

// private:
//     Lock &_lock;
// };